﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class JoyPadEvent : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
	public JoyPad joyPad;

	const int noPointerId = -100;

	/// <summary>
	/// 用于多点触控
	/// </summary>
	int m_PointerId = noPointerId;
	/// <summary>
	/// 位置记录
	/// </summary>
	Vector2 m_StartPos;

	private bool m_HasPointerDown;

	//private Vector2 m_StartMousePos;

	Vector2 GetUGUIPosition (PointerEventData eventData)
	{
		Vector2 pos;
		RectTransformUtility.ScreenPointToLocalPointInRectangle(this.transform as RectTransform, eventData.position, eventData.pressEventCamera, out pos);
		return pos;
	}

	public void OnPointerDown (PointerEventData eventData)
	{
		GameDebug.Log($" OnPointerDown  {eventData.pointerId}");
		if (m_PointerId == noPointerId)
		{
			// 标识为开始
			m_PointerId = eventData.pointerId;

			//Debug.Log("OnPointerDown: " + eventData.position);

			Vector2 startPosition = Input.mousePosition; //GetUGUIPosition(eventData);
			m_StartPos = startPosition;
			this.joyPad.SetPosition(startPosition);

		}
	}
	
	

    public const int limitMax = 100;
    public const int limitMin = 20;
	public void OnDrag(PointerEventData eventData)
	{
		if (joyPad.stayStopMode)
		{
			if (m_PointerId == eventData.pointerId)
			{
				//GameDebug.Log("Drag");
				//Debug.Log("OnDrag: " + eventData.position);

				Vector2 position = Input.mousePosition;
				Vector2 offset = GetOffset(position);

				this.joyPad.SetBallOffset(offset);
			}
		}
	}

    private Vector2 m_OldPos;
    Vector2 GetOffset(Vector2 position)
    {
	    if (joyPad.relativeMode)
	    {
			if (m_HasGetRelativeOffset)
			{
				Vector2 offset = position - m_OldPos;

				m_OldPos = position;

				return offset;
			}
            else
            {
				m_HasGetRelativeOffset = true;
				m_OldPos = position;
				return Vector2.zero;
			}
	    }
	    else
	    {
		    Vector2 offset = position - m_StartPos;

		    // 范围限定
		    float sqrMagnitude = offset.sqrMagnitude;
		    if (sqrMagnitude > limitMax * limitMax)
		    {
			    offset = offset.normalized * limitMax;
		    }
		    else if (sqrMagnitude < limitMin * limitMin)
		    {
			    offset = Vector2.zero;
		    }

		    return offset;
	    }
    }


    public void OnPointerUp (PointerEventData eventData)
	{
		if (m_PointerId == eventData.pointerId)
		{
			// 标识为结束
			m_PointerId = noPointerId;

            Vector2 position = GetUGUIPosition(eventData);
            Vector2 offset = GetOffset(position);

            this.joyPad.OnPointerUp(offset);
			// this.joinPad.ResetPosition();
			m_HasGetRelativeOffset = false;
		}
		
	}

    List<RaycastResult> results = new List<RaycastResult>();

    private float m_AvoidCheckRangeMinX;
    private float m_AvoidCheckRangeMaxX;
    private float m_AvoidCheckRangeMinY;
    private float m_AvoidCheckRangeMaxY;

    public void SetAvoidCheckRange(float avoidCheckRangeMinX,float avoidCheckRangeMaxX,float avoidCheckRangeMinY, float avoidCheckRangeMaxY )
    {
	    m_AvoidCheckRangeMinX = avoidCheckRangeMinX;
	    m_AvoidCheckRangeMaxX = avoidCheckRangeMaxX;
	    m_AvoidCheckRangeMinY = avoidCheckRangeMinY;
	    m_AvoidCheckRangeMaxY = avoidCheckRangeMaxY;
    }

    public bool CheckInAvoidRange(Vector3 touchPosition)
    {
	    if (touchPosition.x > m_AvoidCheckRangeMinX
	        && touchPosition.x < m_AvoidCheckRangeMaxX
	        && touchPosition.y > m_AvoidCheckRangeMinY
	        && touchPosition.y < m_AvoidCheckRangeMaxY)
	    {
#if UNITY_EDITOR
		    GameDebug.Log($"点击到避免区域");
#endif
		    return true;
	    }

	    return false;
    }

	bool m_HasGetRelativeOffset;
	private void Update()
	{
		var mousePosition = Input.mousePosition;

		if (EventSystem.current != null)
		{
			if (EventSystem.current.IsPointerOverGameObject(0) || EventSystem.current.IsPointerOverGameObject(-1))
			{
				PointerEventData pointerEventData = new PointerEventData(EventSystem.current);

				pointerEventData.position = mousePosition;

				EventSystem.current.RaycastAll(pointerEventData, results);

				if (results.Count > 1) return;

				bool containThis = false;
				for (int i = 0; i < results.Count; i++)
				{
					if (results[i].gameObject.Equals(this.gameObject))
					{
						containThis = true;
						break;
					}
				}

				if (!containThis)
				{
					return;
				}
			}

		}
		
		if (!joyPad.stayStopMode)
		{
			if (m_PointerId != noPointerId)
			{
				//GameDebug.Log("Drag");
				//Debug.Log("OnDrag: " + eventData.position);

				Vector2 position = Input.mousePosition;// GetUGUIPosition(eventData);
				Vector2 offset = GetOffset(position);

				this.joyPad.SetBallOffset(offset);
			}

			return;
		}
	    
	    bool pointerUp = false;
        if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1))
        {
	        pointerUp = true;
        }

        if (pointerUp)
        {
	        if (m_HasPointerDown)
	        {
		        //this.joinPad.ResetPosition();
		        if (Input.touchCount > 1)
		        {
			        //GameDebug.Log($"touch count 2 : {Input.GetTouch(0).position}   {Input.GetTouch(1).position}  in avoid range:{CheckInAvoidRange(Input.GetTouch(0).position)}  {CheckInAvoidRange(Input.GetTouch(1).position)}   m_AvoidCheckRangeMinX:{m_AvoidCheckRangeMinX}   m_AvoidCheckRangeMaxX:{m_AvoidCheckRangeMaxX}   m_AvoidCheckRangeMinY:{m_AvoidCheckRangeMinY}   m_AvoidCheckRangeMaxY:{m_AvoidCheckRangeMaxY}");
			        if (!CheckInAvoidRange(Input.GetTouch(1).position))
			        {
				        this.joyPad.OnPointerUp(Input.GetTouch(1).position);
			        }
			        else
			        {
				        return;
			        }
		        }
		        else
		        {
			        this.joyPad.OnPointerUp(mousePosition);
		        }

		        m_HasPointerDown = false;
				m_HasGetRelativeOffset = false;
	        }
	        return;
        }


        if (Application.platform != RuntimePlatform.WindowsEditor)
        {
	        if (Input.touchCount > 0)
	        {
		        mousePosition = Input.GetTouch(0).position;
	        }
        }
        
        if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1))
	    {
		    if (Input.GetMouseButtonDown(0))
		    {
			    //m_StartMousePos = Input.mousePosition;
			    Vector3 position = PanelCommon.uiCamera.ScreenToWorldPoint(mousePosition);

			    this.joyPad.SetPosition(position);

			    m_StartPos = position;
			    m_OldPos = position;
			    m_HasPointerDown = true;
			    //GameDebug.LogError("GetMouseButtonDown");
		    }

		    this.joyPad.OnPointerDown();
	    }        
	    else if (Input.GetMouseButton(0))
	    {
		    m_HasPointerDown = true;
            //if (m_HasPointerDown)
            {
	            Vector3 position = PanelCommon.uiCamera.ScreenToWorldPoint(mousePosition);

                Vector2 offset = GetOffset(position);

                if (!joyPad.relativeMode &&  offset.magnitude < 0.05f)
                {
                    //if (!m_HasEnterStay)
                    {
                        //m_HasEnterStay = true;
                        
                        //if (Time.frameCount % 2 == 0)
                        
                        
	                    this.joyPad.OnPointerStay(offset);
/*#if UNITY_EDITOR
						GameDebug.Log($"joinPad stay:{offset}");
#endif*/
                        
                    }
                }
                else
                {
                    //m_HasEnterStay = false;

                    //if (Time.frameCount % 2 == 0)
                    {
                        this.joyPad.SetBallOffset(offset);
#if UNITY_EDITOR
//                        GameDebug.Log($"joinPad move:{offset}");
#endif
                    }
                }
            }
	    }
        
	   
    }
}